import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  queryProduceQuestionList,
  deleteProduceQuestion,
  addOrUpdateProduceQuestion,
  uploadProduceExcel
} from "@/api/exam";
import { addDialog, closeDialog } from "@/components/ReDialog";
import { type FormItemProps } from "../utils/types";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h } from "vue";
import { useRouter } from "vue-router";

export function useRole() {
  const typeData = ref([
    { id: 0, name: "判断题" },
    { id: 1, name: "单选题" },
    { id: 2, name: "多选题" },
    { id: 3, name: "案例分析" }
  ]);

  const router = useRouter();

  const searchForm = reactive({
    title: "",
    type: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      minWidth: 30,
      type: "index",
      index: (index: number) => {
        return (pagination.currentPage - 1) * pagination.pageSize + (index + 1);
      }
    },
    {
      label: "类型",
      prop: "type",
      minWidth: 60,
      formatter: row => {
        switch (row.type) {
          case 0:
            return "判断题";
          case 1:
            return "单选题";
          case 2:
            return "多选题";
          case 3:
            return "案例分析";
        }
      }
    },
    {
      label: "题目",
      prop: "title",
      minWidth: 150,
      cellRenderer: ({ row }) => (
        <el-popover effect="light" trigger="hover" placement="left" width="300">
          {{
            default: () => {
              return (
                <>
                  <el-card>
                    <div v-html={row.title} />
                  </el-card>
                </>
              );
            },
            reference: () => {
              // 去掉 HTML标签
              let result = row.title.replace(/(<([^>]+)>)/gi, "");
              //end
              const size = result.length;
              if (size > 15) {
                result = result.slice(0, 15) + "...";
              }
              return <div v-html={result} />;
            }
          }}
        </el-popover>
      )
    },
    {
      label: "正确答案",
      prop: "question",
      minWidth: 60,
      formatter: row => {
        switch (row.question) {
          case "0":
            return "错误";
          case "1":
            return "正确";
          default:
            return row.question;
        }
      }
    },
    {
      label: "分值",
      prop: "score",
      minWidth: 50
    },
    {
      label: "创建时间",
      prop: "addtime",
      minWidth: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 250,
      slot: "operation"
    }
  ];

  function handleDelete(row) {
    deleteProduceQuestion(row)
      .then(res => {
        if (res.success) {
          message(`您删除了正式题库序号为"${row.id}"的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message("删除数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("删除数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  const handleUpload = async file => {
    const form = new FormData();
    form.append("file", file);
    uploadProduceExcel(form)
      .then(res => {
        if (res.success) {
          message("导入成功", { type: "success" });
          onSearch();
          return false;
        } else {
          message("导入失败:" + res.errMsg, { type: "error" });
          return false;
        }
      })
      .catch(error => {
        message("导入失败:" + JSON.stringify(error), { type: "error" });
        return false;
      });
  };

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    queryProduceQuestionList({
      title: searchForm.title,
      type: searchForm.type,
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage
    })
      .then(res => {
        if (res.success) {
          dataList.value = res.data.list;
          pagination.total = res.data.total;
          loading.value = false;
        } else {
          message("查询数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("查询数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}正式题库`,
      props: {
        formInline: {
          id: row?.id ?? "",
          pid: row?.pid ?? "0",
          type: row?.type ?? 0,
          title: row?.title ?? "",
          score: row?.score ?? 0,
          del: row?.del ?? 0,
          question: row?.question ?? "",
          description: row?.description ?? "",
          addtime: row?.addtime ?? "",
          updatetime: row?.updatetime ?? ""
        }
      },
      width: "60%",
      draggable: true,
      fullscreen: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      footerButtons: [
        {
          label: "取消",
          type: "info",
          btnClick: ({ dialog: { options, index } }) => {
            closeDialog(options, index);
          }
        },
        {
          label: "确定",
          type: "success",
          btnClick: ({ dialog: { options, index } }) => {
            const FormRef = formRef.value.getRef();
            const curData = options.props.formInline as FormItemProps;
            function chores() {
              message(
                `您${title}了正式题库名称为"${curData.title}"的这条数据`,
                {
                  type: "success"
                }
              );
              closeDialog(options, index); // 关闭弹框
              onSearch(); // 刷新表格数据
            }
            FormRef.validate(valid => {
              if (valid) {
                addOrUpdateProduceQuestion(curData)
                  .then(res => {
                    if (res.success) {
                      chores();
                    } else {
                      message("提交失败:" + res.errMsg, { type: "error" });
                    }
                  })
                  .catch(error => {
                    message("提交失败:" + JSON.stringify(error), {
                      type: "error"
                    });
                  });
              }
            });
          }
        }
      ]
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    typeData,
    searchForm,
    loading,
    columns,
    dataList,
    pagination,
    router,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleUpload
  };
}
